﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Web;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;

namespace RequestLog_State_Middleware.Middleware
{
    public class RequestRecordMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<RequestRecordMiddleware> _logger;

        public RequestRecordMiddleware(RequestDelegate next, ILogger<RequestRecordMiddleware> logger)
        {
            _logger = logger;
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var request = context.Request;
            if (request.Method == HttpMethods.Post)
            {
                var buffer = new byte[Convert.ToInt32(request.ContentLength)];
                await request.Body.ReadAsync(buffer, 0, buffer.Length);
                var bodyString = Encoding.UTF8.GetString(buffer);
                _logger.LogInformation($"http protocol:{request.Protocol},host:{request.Host},path:{request.Path}");
                _logger.LogInformation($"requst body content:{bodyString}");
            }

            if (request.Method == HttpMethods.Get)
            {
                _logger.LogInformation($"http protocol:{request.Protocol},host:{request.Host},path:{request.Path}");
                _logger.LogInformation($"queryString:{HttpUtility .UrlDecode(request.QueryString.Value)}");
            }

            await _next(context);
        }
    }

    public static class RequestRecordMiddlewareExtensions
    {
        public static IApplicationBuilder UseRequstRecordLog(this IApplicationBuilder app)
        {
            return app.UseMiddleware<RequestRecordMiddleware>();
        }
    }

}
